package com.bfly.mall.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.ResponseUtil;
import com.bfly.common.json.JsonUtil;
import com.bfly.common.page.Pager;
import com.bfly.common.util.FileUtil;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.config.ResourceConfigure;
import com.bfly.core.context.PagerThreadLocal;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.core.security.ActionModel;
import com.bfly.core.security.Login;
import com.bfly.core.security.PermissionCheck;
import com.bfly.mall.wechat.dto.WeChatMpMaterialFormDTO;
import com.bfly.mall.wechat.entity.WeChatMp;
import com.bfly.mall.wechat.entity.WeChatMpMaterial;
import com.bfly.mall.wechat.enums.WeChatMpMaterialEnum;
import com.bfly.mall.wechat.mp.dto.WeChatMpAddForeverMaterialRequest;
import com.bfly.mall.wechat.mp.dto.WeChatMpAddForeverMaterialResponse;
import com.bfly.mall.wechat.mp.service.WeChatMPAPi;
import com.bfly.mall.wechat.service.IWeChatMpMaterialService;
import com.bfly.mall.wechat.service.IWeChatMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 微信公众号素材 Controller
 *
 * @author 长沙商脉科技有限公司
 * @date 2021/1/4 14:36
 */
@RestController
@RequestMapping(value = {"/manage/wechat/mp/material"})
public class WeChatMpMaterialController extends BaseController {

    @Autowired
    private IWeChatMpMaterialService weChatMpMaterialService;
    @Autowired
    private IWeChatMpService weChatMpService;

    /**
     * 微信公众号素材列表
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/4 14:38
     */
    @GetMapping(value = "/list")
    public void mpMaterialList(HttpServletResponse response, HttpServletRequest request, @RequestParam("platformId") int platformId, @RequestParam("type") String type) {
        PagerThreadLocal.set(request);

        Map<String, Object> param = new HashMap<>();
        param.put("platform_id", platformId);
        param.put("type", type);
        boolean isNews = WeChatMpMaterialEnum.NEWS.getType().equalsIgnoreCase(type);
        if (isNews) {
            param.put("seq", 0);
        }
        Pager<WeChatMpMaterial> page = weChatMpMaterialService.getPage(param);
        if (page != null && page.getData() != null && isNews) {
            List<WeChatMpMaterial> materials = page.getData();
            Iterator<WeChatMpMaterial> iterator = materials.iterator();
            while (iterator.hasNext()) {
                WeChatMpMaterial material = iterator.next();
                if (material.isMore()) {
                    List<WeChatMpMaterial> subNews = weChatMpMaterialService.getSubNews(material.getMediaId());
                    material.setNews(subNews);
                }
            }
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(page));
    }

    /**
     * 新增素材
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/9 18:02
     */
    @PostMapping(value = "/add")
    @ActionModel("新增素材")
    public void addMpMaterial(HttpServletResponse response, @RequestBody WeChatMpMaterialFormDTO... formDTOs) {
        weChatMpMaterialService.save(formDTOs);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 编辑图文素材
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/10 11:32
     */
    @PostMapping(value = "/edit")
    @ActionModel("编辑图文素材")
    public void editNewsMaterial(HttpServletResponse response, @RequestBody WeChatMpMaterialFormDTO... formDTOs) {
        weChatMpMaterialService.edit(formDTOs);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 删除素材
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/10 11:33
     */
    @PostMapping(value = "/delete")
    @ActionModel(value = "删除素材")
    public void delFreightTemplate(HttpServletResponse response, @RequestParam("platformId") int platformId, @RequestParam("mediaId") String mediaId) {
        weChatMpMaterialService.remove(platformId, mediaId);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
    }

    /**
     * 素材详情---针对图文素材
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/12 11:09
     */
    @GetMapping(value = "/news/info")
    public void getNewsMaterial(HttpServletResponse response, @RequestParam("mediaId") String mediaId, @RequestParam("platformId") int platformId) {
        WeChatMp weChatMp = weChatMpService.get(platformId);
        if (weChatMp == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的平台类型!");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("type", WeChatMpMaterialEnum.NEWS.getType());
        param.put("media_id", mediaId);
        param.put("platform_id", platformId);
        List<WeChatMpMaterial> materials = weChatMpMaterialService.getList(param);
        Collections.sort(materials);
        ResponseUtil.writeJson(response, ResponseData.getSuccess(materials));
    }

    /**
     * 上传图文内容图片
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/19 21:53
     */
    @PostMapping(value = "/news/upload")
    @PermissionCheck(required = false)
    public void uploadNewsContentImgMaterial(@RequestPart MultipartFile file, @RequestParam("platformId") int platformId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        WeChatMp weChatMp = weChatMpService.get(platformId);
        if (weChatMp == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的平台类型!");
        }

        String fileName = FileUtil.getRandomName() + FileUtil.getFileSuffix(file.getOriginalFilename());
        String targetPath = ResourceConfigure.getConfig().getTempRootPath() + File.separator + fileName;
        File tempFile = new File(targetPath);

        WeChatMpAddForeverMaterialRequest materialRequest = new WeChatMpAddForeverMaterialRequest();
        materialRequest.setFile(tempFile.getPath());
        materialRequest.setFileName(file.getOriginalFilename());
        materialRequest.setType(file.getContentType());
        file.transferTo(tempFile);

        WeChatMpAddForeverMaterialResponse materialResponse = WeChatMPAPi.addNewsContentImgMaterial(weChatMp.getAppId(), weChatMp.getAppSecret(), materialRequest);
        JSONObject json = new JSONObject();
        json.put("url", materialResponse.getUrl());
        json.put("size", file.getSize());
        ResponseUtil.writeJson(response, ResponseData.getSuccess(json));
    }


    /**
     * 获得多媒体流
     *
     * @author 长沙商脉科技有限公司
     * @date 2021/1/16 15:14
     */
    @GetMapping(value = "/stream")
    @PermissionCheck(required = false)
    @Login(required = false)
    public void getMediaMaterial(HttpServletResponse response, @RequestParam("mediaId") String mediaId, @RequestParam("platformId") int platformId) {
        WeChatMp weChatMp = weChatMpService.get(platformId);
        if (weChatMp == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的平台类型!");
        }
        WeChatMpMaterial material = weChatMpMaterialService.getMaterial(platformId, mediaId);
        byte[] bytes = WeChatMPAPi.getImageOrVoiceMaterial(weChatMp.getAppId(), weChatMp.getAppSecret(), mediaId);
        if ("image".equalsIgnoreCase(material.getType()) || "voice".equalsIgnoreCase(material.getType())) {
            try (ServletOutputStream outputStream = response.getOutputStream()) {
                outputStream.write(bytes);
            } catch (Exception ex) {
                throw new ServiceResponseException(SysError.ERROR, ex.getMessage());
            }
        } else if ("video".equalsIgnoreCase(material.getType())) {
            String str = new String(bytes);
            JSONObject json = JsonUtil.parse(str, JSONObject.class);
            ResponseUtil.writeJson(response, ResponseData.getSuccess(json.getString("down_url")));
        } else {
            ResponseUtil.writeJson(response, ResponseData.getSuccess(""));
        }
    }
}